<?php

namespace app\admin\controller\auth;

use app\admin\model\CaAuthGroup;
use app\admin\model\CaAuthGroupAccess;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;
use think\Validate;
use think\Db;
/**
 * 管理员管理
 *
 * @icon fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Admin extends Backend
{

    /**
     * @var \app\admin\model\CaAdmin
     */
    protected $model = null;
    protected $selectpageFields = 'id,username,nickname,avatar';
    protected $searchFields = 'id,username,nickname';
    protected $noNeedRight = ['get_rules','get_rule_list','selectpage','get_province','get_member'];
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('CaAdmin');

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $groupList = collection(CaAuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();

            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $ids=input("ids");
            if (isset($ids)){
                $result[13]='&nbsp;└ 院校组';
            }
            $groupdata = $result;
        }
        $this->view->assign('groupdata', $groupdata);
        $this->assignconfig("admin", ['id' => $this->auth->id]);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $childrenGroupIds = $this->childrenGroupIds;
            $groupName = CaAuthGroup::where('id', 'in', $childrenGroupIds)
                ->column('id,name');
            $authGroupList = CaAuthGroupAccess::where('group_id', 'in', $childrenGroupIds)
                ->field('uid,group_id')
                ->select();


            $adminGroupName = [];
            foreach ($authGroupList as $k => $v) {
                if (isset($groupName[$v['group_id']])) {
                    $adminGroupName[$v['uid']][$v['group_id']] = $groupName[$v['group_id']];
                }
            }
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $adminGroupName[$this->auth->id][$n['id']] = $n['name'];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->where('id', 'in', $this->childrenAdminIds)
                ->where(" status='normal'")
                ->field(['password', 'salt', 'token'], true)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {
                $groups = isset($adminGroupName[$v['id']]) ? $adminGroupName[$v['id']] : [];
                    $v['groups'] = implode(',', array_keys($groups));
                    $v['groups_text'] = implode(',', array_values($groups));
            }
            unset($v);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);

        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        $data=input('');
        $ids=isset($data['ids'])?$data['ids']:'';
        $s_name=isset($data['s_name'])?$data['s_name']:'';
        $type=isset($data['type'])?$data['type']:'';
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                if (!Validate::is($params['password'], '\S{6,16}')) {
                    $this->error(__("Please input correct password"));
                }
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
                $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                $params['add_user']=session('admin.id');
               $id = $this->model->where(['username'=>$params['username']])->value('id');
               if($id){
                   $this->error('该手机号账号已存在');
               }
//                $params['province']=join(",",$params['province']);
//                dump($type);exit;
                $result = $this->model->save($params);
//                $result=1;
                if ($result === false) {
                    $this->error($this->model->getError());
                }
                if ($type=='1'){
                    $group[] = 13;
                }elseif ($type=='2'){
                    $group[] = 10;
                }else{
                    $group = $this->request->post("group/a");
                    $group = array_intersect($this->childrenGroupIds, $group);
                }

                //过滤不允许的组别,避免越权
                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
                }
                model('CaAuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
        $this->assign('data',$data);
        if ($ids){
            $groupids = [];
            if ($type==1){
                $groupids[] = 13;
            }else{
                $groupids[] = 10;
            }
            $this->view->assign("groupids", $groupids);
        }
        $pro=get_pro();
        $this->view->assign("pro", $pro);
        $this->view->assign("ids", $ids);
        $this->view->assign("type", $type);
        $this->view->assign("s_name", $s_name);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (!in_array($row->id, $this->childrenAdminIds)) {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                if ($params['password']) {
                    if (!Validate::is($params['password'], '\S{6,16}')) {
                        $this->error(__("Please input correct password"));
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                } else {
                    unset($params['password'], $params['salt']);
                }
//                $params['province']=join(",",$params['province']);

                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('CaAdmin');
                $adminValidate->rule([
                    'username' => 'require|unique:admin,username,' . $row->id,
//                    'email'    => 'require|email|unique:admin,email,' . $row->id,
                    'password' => 'regex:\S{32}',
                ]);
                $result = $row->validate('CaAdmin.edit')->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }

                // 先移除所有权限
                model('CaAuthGroupAccess')->where('uid', $row->id)->delete();

                $group = $this->request->post("group/a");

                // 过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);

                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $row->id, 'group_id' => $value];
                }
                model('CaAuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
        $grouplist = $this->auth->getGroups($row['id']);
        $groupids = [];
        foreach ($grouplist as $k => $v) {
            $groupids[] = $v['id'];
        }
        $this->view->assign("row", $row);
        $pro=get_pro();
        $this->view->assign("pro", $pro);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $ids = array_intersect($this->childrenAdminIds, array_filter(explode(',', $ids)));
            // 避免越权删除管理员
            $childrenGroupIds = $this->childrenGroupIds;
            $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function ($query) use ($childrenGroupIds) {
                $query->name('ca_auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
            })->select();
            if ($adminList) {
                $deleteIds = [];
                foreach ($adminList as $k => $v) {
                    $deleteIds[] = $v->id;
                }
                $deleteIds = array_values(array_diff($deleteIds, [$this->auth->id]));
                if ($deleteIds) {
                    $this->model->destroy($deleteIds);
                    model('CaAuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
                    $this->success();
                }
            }
        }
        $this->error(__('You have no permission'));
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }

    /**
     * 下拉搜索
     */
    public function selectpage()
    {
        $this->dataLimit = 'auth';
        $this->dataLimitField = 'id';
        return parent::selectpage();
    }


    public function province_auth(){
//        dump($this->auth);exit;
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $this->searchFields = 'm.nickname';
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $con=[];
            $group_id=input('group_id')?input('group_id'):7;
            $con['b.group_id']=$group_id;
            $where_str='';
//            if (input('province') && input('province')!='all'){
//                $where_str.=" id IN(".input('province').")";
//            }elseif(input('province') && input('province')=='all'){
//                $where_str.=" id IN(2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32)";
//            }else{
//                $where_str.=" id IN(2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32)";
//            }
//            if (input('type'))$con['a.type']=input('type');

            $rules=$this->get_rule_list($group_id);
            $p_list='0';
            $p_rules=Db::name('ca_auth_rule')->field("id")->where('id>1 and pid=0 AND ismenu=1 AND status="normal"')->select();
            if ($p_rules)$p_list=implode(",",array_column($p_rules, 'id'));
            $res=Db::name('ca_auth_rule')
                ->alias('a')
                ->field('a.id,a.title')
                ->join("ca_auth_rule c",'c.id=a.pid','left')
                ->where("a.id IN (".$p_list.")  AND a.ismenu=1 AND a.status='normal' ")
                ->where("a.id IN(".$rules.")")
                ->order('c.weigh desc, a.weigh desc')
                ->select();
//            $type=input('type')?input('type'):'1,2,3,4,5,6';
//            dump($res);exit;
            $type_arr=array_column($res, 'id');
//            dump($type_arr);exit;
//            explode(",",$type);
            $province_arr=DB::name('province')
                ->where('id<96 and id>1')
                ->where($where_str)
                ->order('sort desc')
                ->cache(300)
                ->select();
            $arr=[];
                for ($i=0;$i<count($type_arr);$i++){
                foreach ($province_arr as $k=>&$v){
                    $data=DB::name('ca_auth_province')
                        ->alias('a')
                        ->field("c.title,group_concat(m.nickname ORDER BY m.id ASC Separator ';') as all_name")
                        ->join('ca_admin m','a.m_id=m.id','left')
                        ->join('ca_auth_rule c','a.type=c.id','right')
                        ->join('ca_auth_group_access b','a.m_id=b.uid','left')
                        ->where($con)
                        ->where(['a.type'=>$type_arr[$i]])
                        ->where("find_in_set(".$v['id'].",a.province)")
                        ->find();
                    $arr[$i]['type']=$type_arr[$i];
                    $arr[$i]['type_name']=$data['title'];
                    $arr[$i][$v['py']]=$data['all_name'];
//                    dump($arr);exit;
                }
            }

            $groups=Db::name('ca_auth_group_access')
                ->alias('a')
                ->field('c.id,c.nickname,group_concat(d.province_name  Separator ",") as all_num')
                ->join('ca_admin c','c.id=a.uid','left')
                ->join('ca_auth_province d','c.id=d.m_id','left')
                ->where("a.group_id=".$group_id."  and c.status='normal'")
//                ->cache(60)
                ->group('a.uid')
                ->select();
                foreach ($groups as $k=>&$v){
                    if ($v['all_num']==null){
                        $v['nums']=0;
                    }else{
                        $v['nums']=count(array_unique(explode(",",$v['all_num'])));
                    }
                }
            $result = array("total" => count($type_arr), "rows" => $arr,"extend" => ['group' =>$groups]);
            return json($result);
        }

        //一级栏目
        $province=get_pro();//省份
        $this->assign('province',$province);
//        $this->assign('pid','3,4,5,6,7,8'); //省份
        $groupList=Db::name('ca_auth_group')
            ->alias('a')
            ->field('a.name,a.id,count(b.uid) as num')
            ->join('ca_auth_group_access b','a.id=b.group_id','right')
            ->join('ca_admin c','c.id=b.uid','left')
            ->where('a.id', 'in', $this->childrenGroupIds)
            ->where("a.id!=1 and a.id!=13 and a.id!=14  and c.status='normal'")
            ->group('b.group_id')
            ->order('sort desc')
            ->cache(60)
            ->select();
        $this->view->assign("groupList", $groupList);
        $this->view->assign("cid", 7);

        return $this->view->fetch();
    }

    public function province_auth_edit(){ //分省权限编辑
//        dump($this->childrenGroupIds);exit;
        $groupList=Db::name('ca_auth_group')
            ->alias('a')
            ->field('a.name,a.id,count(b.uid) as num')
            ->join('ca_auth_group_access b','a.id=b.group_id','right')
            ->join('ca_admin c','c.id=b.uid','left')
            ->where("a.id!=1 and a.id!=13 and a.id!=14  and c.status='normal'")
            ->where('a.id', 'in', $this->childrenGroupIds)
            ->group('b.group_id')
            ->order('sort desc')
            ->cache(60)
            ->select();

//        dump($this->childrenAdminIds);exit;

//        $authList=Db::name('ca_auth_rule')
//            ->alias('a')
//            ->field()
//            ->join('ca_auth_group_access b','')
//            ->where("pid=0 AND ismenu=1 AND status='normal'")
//            ->where()
//            ->select();
//        $this->view->assign("authList", $authList);
        $this->view->assign("groupList", $groupList);

        return $this->view->fetch();
    }


    public function get_rule_list($pid){
        $group=DB::name('ca_auth_group')->field('rules')->where(['id'=>$pid])->find();
        $rules=$group['rules']?$group['rules']:0;
        return $rules;
    }
    public function get_member(){//获取成员
        $pid=input('post.pid');
        if (empty($pid))$this->error('错误');
        $res=DB::name('ca_auth_group_access')
            ->alias('a')
            ->field('m.nickname,m.id')
            ->join('ca_admin m','m.id=a.uid','left')
            ->where("a.group_id=".$pid." AND m.status='normal'")
//            ->group('a.group_id')
            ->select();
        $rules=$this->get_rule_list($pid);
        $authList=Db::name('ca_auth_rule')
            ->field('id,title')
            ->where("pid=0 and id>1 AND ismenu=1 AND status='normal'")
            ->where("id IN(".$rules.")")
            ->order('weigh desc')
            ->select();
//        dump($authList);exit;
        return ['code'=>1,'data'=>$res,'rules'=>$authList];
    }

    public function get_province(){ //获取已有省份
        $mid=input('post.mid');
        $type=input('post.type');
        if (empty($mid) || empty($type))$this->error('错误');
        $res=DB::name('ca_auth_province')
            ->where(['m_id'=>$mid,'type'=>$type])
            ->find();
        $province=get_pro();//省份
        $arr=[];
        if(isset($res['province']))$arr=explode(",",$res['province']);
        return ['code'=>1,'data'=>$arr,'province'=>$province];
    }

    public function get_record(){ //省份结果
        $pid=input('post.pid');
        $mid=input('post.mid');
        if (empty($mid))$this->error('错误');
        $rules=$this->get_rule_list($pid);
        $p_list='0';
        $p_rules=Db::name('ca_auth_rule')->field("id")->where('id>1 and pid=0 AND ismenu=1 AND status="normal"')->select();
        if ($p_rules)$p_list=implode(",",array_column($p_rules, 'id'));
//        dump($p_rules);exit;
        $res=Db::name('ca_auth_rule')
            ->alias('a')
            ->field('IFNULL(b.province_name, "") province_name,a.title')
            ->join("(select province_name,type from app_ca_auth_province where m_id=".$mid.") b ",'b.type=a.id','left')
            ->join("ca_auth_rule c",'c.id=a.pid','left')

            ->where("a.pid IN (".$p_list.")  AND a.ismenu=1 AND a.status='normal' ")
            ->where("a.id IN(".$rules.")")
            ->order('c.weigh desc, a.weigh desc')
            ->select();
//        dump($res);exit;
//        dump(Db::name('ca_auth_rule')->getLastSql());exit;
//        $res=DB::name('ca_auth_province')
//            ->where(['m_id'=>$mid])
//            ->order('type asc')
//            ->select();
        return ['code'=>1,'data'=>$res];

    }

    public function add_province(){ // 省份权限添加
        $mid=input('post.mid');
        $type=input('post.type');
        $province=input('post.province');
        if (empty($mid) || empty($type))$this->error('错误');
        $data=DB::name('ca_auth_province')
            ->where(['m_id'=>$mid,'type'=>$type])
            ->find();
       if ($province){
           $pro=DB::name('province')->field('id,name')->where('id IN('.$province.')')->order('sort desc')->select();
           $pro_name=implode(",",array_column($pro, 'name'));
       }else{
           $pro_name='';
       }

        if (empty($data)){
            $res=DB::name('ca_auth_province')->insert(['m_id'=>$mid,'type'=>$type,'province'=>$province,'province_name'=>$pro_name]);
        }else{
            $res=DB::name('ca_auth_province')
                ->where(['m_id'=>$mid,'type'=>$type])
                ->update(['province'=>$province,'province_name'=>$pro_name]);
        }

//        DB::name('ca_auth_province_list')->where(['m_id'=>$mid,'type'=>$type])->delete();
//        DB::name('ca_auth_province_list')->where(['m_id'=>$mid,'type'=>$type])->delete();



        if ($res)return ['code'=>1,'data'=>$pro_name];
    }

    public function get_rules(){
        $pid=input('post.pid');
        $mid=input('post.mid');
        if (empty($pid))$this->error('错误');
        $rules=$this->get_rule_list($mid);
        $authList=Db::name('ca_auth_rule')
            ->field('id,title')
            ->where("pid=".$pid." and id>1 AND ismenu=1 AND status='normal'")
            ->where("id IN(".$rules.")")
            ->order('weigh desc')
            ->select();
//        dump($authList);exit;
        return ['code'=>1,'data'=>$authList];
    }
}
